package com.idanchuang.count.core.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.idanchuang.component.base.exception.core.ExFactory;
import com.idanchuang.count.IErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author Richard_yyf
 * @version 1.0 2021/6/10
 */
@Slf4j
public class JacksonUtil {

    private static final ObjectMapper MAPPER;

    static {
        MAPPER = new ObjectMapper();
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static <T> T parseObject(byte[] source, Class<T> clazz) {
        try {
            return MAPPER.readValue(source, clazz);
        } catch (IOException e) {
            log.error("json parseObject error, valueAsString: " + new String(source), e);
            throw ExFactory.throwWith(IErrorCode.JSON_ERROR, new String(source));
        }
    }

    public static <T> T parseObject(String valueAsString, Class<T> clazz) {
        try {
            return MAPPER.readValue(valueAsString, clazz);
        } catch (IOException e) {
            log.error("json parseObject error, valueAsString: " + valueAsString, e);
            throw ExFactory.throwWith(IErrorCode.JSON_ERROR, valueAsString);
        }
    }

    public static String toJsonStr(Object object) {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.error("toJson error, object: " + object.toString(), e);
            throw ExFactory.throwWith(IErrorCode.JSON_ERROR, object.toString());
        }
    }
}
